#include <assert.h>
#include <stdlib.h>
#include "pd_define.h"
#include "pd_log.h"
#include "pd_socket.h"
#include "pd_event.h"

int main(int argc, char ** argv)
{
    if (2 > argc)
    {
        PD_LOG(WARN, "Server port must be set\b");
        exit(-1);
    }
    int port = atoi(argv[1]);

    PD_LOG(INFO, "mock_tcp_server main");

    PdSocket *lsock = pd_socket_init_tcp_server(port);
    assert(NULL != lsock);

    PdSocketEvent *ev = pd_event_init();
    PdIOComponent lio;
    lio.sock = lsock;
    int ret = pd_event_add_event(ev, &lio, 1, 0);
    assert(0 == ret);

    while (1)
    {
        PdIOEvent event;
        ret = pd_event_get_events(ev, 10000000, &event, 1);
        if (1 == ret)
        {
            if (&lio == event.ioc)
            {
                PdSocket *csock = pd_socket_accept_tcp_client(event.ioc->sock);
                assert(NULL != csock);

                PdIOComponent *cio = (PdIOComponent*)malloc(sizeof(PdIOComponent));;
                cio->sock = csock;
                ret = pd_event_add_event(ev, cio, 1, 0);
                assert(0 == ret);
            }
            else
            {
                const uint32_t BUFFER_SIZE = 4096;
                char buffer[BUFFER_SIZE];
                if (0 == read(pd_socket_get_fd(event.ioc->sock), buffer, BUFFER_SIZE))
                {
                    PD_LOG(INFO, "client close tcp, peer=[%s]", pd_socket_str_peer(event.ioc->sock));
                    pd_socket_destroy(event.ioc->sock);
                    free(event.ioc);
                }
                else
                {
                    PD_LOG(INFO, "read from peer=[%s], [%s]", pd_socket_str_peer(event.ioc->sock), buffer);
                }
            }
        }
    }
}

